package com.gs.wzmanager.service;

import com.gs.wzmanager.utils.Constant;
import com.gs.wzmanager.utils.DateUtil;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Legolas
 * Date: 2017/10/30 0030
 */
@Service
@EnableScheduling
public class ForcastReviseService{


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //预报稿监听对象
    private FileAlterationMonitor monitorThree = null;
    private FileAlterationObserver observerThree = null;


    //一周预报监听对象
    private FileAlterationMonitor monitorWeek = null;
    private FileAlterationObserver observerWeek = null;

    private Map currentThreeYM = DateUtil.getYearPreMonth();//默认设置前一个月，定时器启动会重新扫描并录入当前月数据
    private Map currentWeekYM = DateUtil.getYearPreMonth();//默认当前年月
    //预报稿监听路径
    private String scanDirThree = null;
    //一周预报监听路径
    private String scanDirWeek = null;

    public FileAlterationObserver getObserverThree() {
        return observerThree;
    }

    public void setObserverThree(FileAlterationObserver observerThree) {
        this.observerThree = observerThree;
    }

    public FileAlterationObserver getObserverWeek() {
        return observerWeek;
    }

    public void setObserverWeek(FileAlterationObserver observerWeek) {
        this.observerWeek = observerWeek;
    }

    public FileAlterationMonitor getMonitorWeek() {
        return monitorWeek;
    }

    public void setMonitorWeek(FileAlterationMonitor monitorWeek) {
        this.monitorWeek = monitorWeek;
    }

    public String getScanDirWeek() {
        return scanDirWeek;
    }

    public void setScanDirWeek(String scanDirWeek) {
        this.scanDirWeek = scanDirWeek;
    }

    public FileAlterationMonitor getMonitorThree() {
        return monitorThree;
    }

    public void setMonitorThree(FileAlterationMonitor monitorThree) {
        this.monitorThree = monitorThree;
    }

    public Map getCurrentThreeYM() {
        return currentThreeYM;
    }

    public void setCurrentThreeYM(Map currentThreeYM) {
        this.currentThreeYM = currentThreeYM;
    }

    public Map getCurrentWeekYM() {
        return currentWeekYM;
    }

    public void setCurrentWeekYM(Map currentWeekYM) {
        this.currentWeekYM = currentWeekYM;
    }

    public String getScanDirThree() {
        return scanDirThree;
    }

    public void setScanDirThree(String scanDirThree) {
        this.scanDirThree = scanDirThree;
    }

    private final static ForcastReviseService instance = new ForcastReviseService();

    @PostConstruct
    public void TimerToScan() throws Exception {

        instance.setScanDirThree(Constant.FORECAST_PATH.THREE + instance.getCurrentThreeYM().get("year") + "/" + instance.getCurrentThreeYM().get("month"));
        instance.setScanDirWeek(Constant.FORECAST_PATH.WEEK + instance.getCurrentThreeYM().get("year") + "/" + instance.getCurrentThreeYM().get("month"));

        //初始化开启监听当前年月目录
        scanThreeRevise(instance);
        scanWeekRevise(instance);

    }


    public void scanThreeRevise(ForcastReviseService param) throws Exception {

        FileAlterationObserver observer = new FileAlterationObserver(
                param.getScanDirThree(),
                (File file) -> (file.getName().endsWith(".txt")));
        observer.addListener(new MyFileListener("THREE"));
        param.setObserverThree(observer);
        //将监听对象放入内存
        param.setMonitorThree(new FileAlterationMonitor(Constant.FORECAST_PATH.FILE_SCAN_MINUTES, observer));
        // 开始监控
        param.getMonitorThree().start();
    }

    public void scanWeekRevise(ForcastReviseService param) throws Exception {

        // 轮询间隔30分钟
        FileAlterationObserver observer = new FileAlterationObserver(
                param.getScanDirWeek(),
                (File file) -> (file.getName().endsWith(".fwz")));
        observer.addListener(new MyFileListener("WEEK"));
        param.setObserverWeek(observer);
        //将监听对象放入内存
        param.setMonitorWeek(new FileAlterationMonitor(Constant.FORECAST_PATH.FILE_SCAN_MINUTES, observer));
        // 开始监控
        param.getMonitorWeek().start();
    }


    @Scheduled(cron="0 0/5 *  * * ?")//每5分钟运行一次
    //@Scheduled(cron="0/10 * *  * * ?")//每10秒钟运行一次test
    public void schedulToRun() {
        //每次取当前年月
        Map currentDate = DateUtil.getYearMonth();
        //如果当前年月和记录的不一致,重新设置监听目录
        String currentThreeDir = Constant.FORECAST_PATH.THREE + currentDate.get("year") + "/" + currentDate.get("month");
        String currentWeekDir = Constant.FORECAST_PATH.WEEK + currentDate.get("year") + "/" + currentDate.get("month");
        //如果当前时间已经更新，且目录已经更新,则将内存中的当前时间和目录更新
        if (!DateUtil.equal(currentDate, instance.getCurrentThreeYM()) && new File(currentThreeDir).exists()) {
            //处理新生成文件夹的初始值
            instance.setCurrentThreeYM(currentDate);
            instance.setScanDirThree(currentThreeDir);
            try {
                //去除旧目录的监听//FileAlterationMonitor更换监听目录只需要重新设置FileAlterationObserver即可
                instance.getMonitorThree().removeObserver(instance.getObserverThree());
                //添加新目录的监听器
                FileAlterationObserver observer = new FileAlterationObserver(
                        currentThreeDir,
                        (File file) -> (file.getName().endsWith(".txt")));
                observer.addListener(new MyFileListener("THREE"));
                instance.getMonitorThree().addObserver(observer);
                //将当前扫描器放入内存
                instance.setObserverThree(observer);
                logger.info("TimerThreeToRun->{}", "扫描目录改变，当前年月:" + instance.getCurrentThreeYM() + "====扫描目录:" + instance.getScanDirThree());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //Week周报业务
        if (!DateUtil.equal(currentDate, instance.getCurrentWeekYM()) && new File(currentWeekDir).exists()) {
            //处理新生成文件夹的初始值

            //dealDirWeekInitFile(currentWeekDir);
            instance.setCurrentWeekYM(currentDate);
            instance.setScanDirWeek(currentWeekDir);
            try {
                instance.getMonitorWeek().removeObserver(instance.getObserverWeek());
                //添加新目录的监听器
                FileAlterationObserver observer = new FileAlterationObserver(
                        currentWeekDir,
                        (File file) -> (file.getName().endsWith(".fwz")));
                observer.addListener(new MyFileListener("WEEK"));
                instance.getMonitorWeek().addObserver(observer);

                instance.setObserverWeek(observer);
                logger.info("TimerWeekToRun->{}", "扫描目录改变，当前年月:" + instance.getCurrentWeekYM() + "====扫描目录:" + instance.getScanDirWeek());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}




